/*
 *  Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 *  This file is part of e3utils.
 *
 *  e3utils is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  e3utils is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with e3utils. If not, see <https://www.gnu.org/licenses/>.
 */

package load_balancer

import (
	"log"
	"math"

	"gitee.com/ameise84/e3ds/heap"
)

func NewBalancerBest[T Context]() Balancer[T] {
	return &bestBalancer[T]{
		h:             heap.NewMin[uint64, *contextWrap[T]](64),
		mp:            make(map[uint64]struct{}),
		autoAddWeight: 1,
	}
}

type bestBalancer[T Context] struct {
	h             heap.Heap[uint64, *contextWrap[T]]
	mp            map[uint64]struct{}
	autoAddWeight int //当获取时,自动添加权重值,默认1
	zeroT         T
}

func (b *bestBalancer[T]) Mode() Mode {
	return BestMode
}

func (b *bestBalancer[T]) Count() int {
	return len(b.mp)
}

func (b *bestBalancer[T]) Register(ctx T) error {
	id := ctx.LoadBalancerID()
	item := &contextWrap[T]{ctx: ctx, weight: 0} //注册时默认最优
	_, err := b.h.Push(item)
	if err != nil {
		return err
	}
	b.mp[id] = struct{}{}
	return nil
}

func (b *bestBalancer[T]) UnRegister(id uint64) (T, bool) {
	if _, ok := b.mp[id]; ok {
		v, _ := b.h.Remove(id)
		if v.weight > 0 {
			log.Printf("bestBalancer UnRegister -> Id[%d] is using\n", id)
		}
		delete(b.mp, id)
		return v.ctx, true
	}
	return b.zeroT, false
}

func (b *bestBalancer[T]) Clean() []T {
	out := make([]T, 0, len(b.mp))
	vs := b.h.CleanToSlice()
	for _, v := range vs {
		out = append(out, v.ctx)
	}
	b.mp = map[uint64]struct{}{}
	return out
}

func (b *bestBalancer[T]) Range(f func(T) bool) {
	b.h.Range(func(v *contextWrap[T]) bool {
		return f(v.ctx)
	})
}

func (b *bestBalancer[T]) TakeByID(id uint64) (T, bool) {
	if v, ok := b.h.Find(id); ok {
		v.weight += b.autoAddWeight
		if v.weight < 0 {
			v.weight = math.MaxInt
		}
		b.h.Update(v.ctx.LoadBalancerID(), v)
		return v.ctx, true
	}
	return b.zeroT, false
}

func (b *bestBalancer[T]) TakeNext(uint64) (T, error) {
	v, err := b.h.Peek()
	if err != nil {
		return b.zeroT, err
	}
	v.weight += b.autoAddWeight
	b.h.Update(v.ctx.LoadBalancerID(), v)
	return v.ctx, nil
}

func (b *bestBalancer[T]) SetAutoPriWt(weight int16) {
	b.autoAddWeight = int(weight)
}

func (b *bestBalancer[T]) UpdatePriWt(id uint64, weight int) {
	if v, ok := b.h.Find(id); ok {
		if weight < 0 {
			weight = 0
		}
		v.weight = weight
		b.h.Update(id, v)
	}
}
